'use strict';

const Controller = require('egg').Controller;
const md5 = require('md5')

class Login extends Controller {
  // 获取用户信息
  async getInfo() {
    const {
      ctx
    } = this
    try {
      let user = await ctx.model.User.findOne({
        where: {
          user_id: ctx.state.user.user_id
        }
      })
      if (user) {
        ctx.body = {
          code: 200,
          data: {
            user_id: user.user_id,
            username: user.username,
            auth: user.auth
          },
          msg: '登录成功'
        }
      }
    } catch (error) {
      ctx.body = {
        code: 0,
        type: 'GET_INFO_ERROR',
        msg: '获取用户信息失败'
      }
    }
  }
  // 获取token
  async login() {
    const {
      ctx,
      app
    } = this;
    let username = ctx.request.body.username
    let password = ctx.request.body.password
    try {
      if (!username) {
        throw new Error('用户名参数错误')
      } else if (!password) {
        throw new Error('密码参数错误')
      }
    } catch (error) {
      ctx.body = {
        code: 0,
        type: 'PARAMS_ERROR',
        msg: error.message
      }
      return
    }
    try {
      let user = await ctx.model.User.findOne({
        where: {
          username,
          password: md5(password),
          lock: '1'
        }
      })
      if (user) {
        const token = app.jwt.sign({
          user_id: user.user_id,
          auth: user.auth,
          username: user.username,
        }, app.config.jwt.secret, {
          expiresIn: '1h',
        });

        ctx.body = {
          code: 200,
          data: {
            token
          },
          msg: '获取token成功'
        }
      } else {
        ctx.body = {
          code: 0,
          msg: '密码错误'
        }
      }
    } catch (error) {
      ctx.body = {
        code: 0,
        type: 'LOGIN_ERROR',
        msg: '登录失败'
      }
    }
  }
}

module.exports = Login;